package processes

import (
	"github.com/astaxie/beego/toolbox"
	"github.com/rcrowley/go-metrics"
	"github.com/shirou/gopsutil/process"
)

var (
	Register metrics.Registry
)

func init() {
	Register = metrics.NewRegistry()
	tk := toolbox.NewTask("GetStatusTask", "*/5 * * * * *", GetStatusTask)
	toolbox.AddTask("GetStatusTask", tk)
}

func GetStatusTask() error {
	status1, err := process.Processes()
	if err != nil {
		Register.UnregisterAll()
		return err
	}

	var running int64
	var zombie int64
	var sleep int64

	for _, pro := range status1 {
		b, _ := pro.Status()
		switch b {
		case "R":
			running += 1
		case "Z":
			zombie += 1
		case "S":
			sleep += 1
		}
	}
	metrics.GetOrRegisterGauge("running", Register).Update(running)
	metrics.GetOrRegisterGauge("zombie", Register).Update(zombie)
	metrics.GetOrRegisterGauge("sleep", Register).Update(sleep)
	return nil
}
